﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace ResourceTypeConfigurationApp
{
    public partial class fmNewDevice : Form
    {
        public fmNewDevice()
        {
            InitializeComponent();
        }

        private async void btnNew_Click(object sender, EventArgs e)
        {

            DataTable dtSite = SiteBindingSource.DataSource as DataTable;


            if (dtSite == null || !dtSite.AsEnumerable().Any(x => x["IsSelected"].ToString() == "True"))
            {
                MessageBox.Show("请先勾选数据");
                return;
            }

            var drSite = dtSite.AsEnumerable().FirstOrDefault(x => x["IsSelected"].ToString() == "True");

            DataTable dtA = DeviceBindingSource.DataSource as DataTable;
            if (dtA == null || !dtA.AsEnumerable().Any(x => x["IsSelected"].ToString() == "True"))
            {
                MessageBox.Show("请先勾选数据");
                return;
            }
            if (!cbPt.Checked && !cbWh.Checked)
            {
                MessageBox.Show("请先勾选插入功率设备或者电量设备！");
                return;
            }
            if (string.IsNullOrWhiteSpace(txtEndDate.Text))
            {
                MessageBox.Show("下次更新时间不可为空！");
                return;
            }
            string dateTimeString = txtEndDate.Text;
            string format = "yyyyMMddHHmm";
            if (!DateTime.TryParseExact(dateTimeString, format, null, System.Globalization.DateTimeStyles.None, out DateTime result))
            {
                MessageBox.Show("下次更新时间的时间格式错误！");
                return;
            }
            int isDel = 1;
            if (cbOn.Checked)
            {
                isDel = 0;
            }

            var drs = dtA.AsEnumerable().Where(x => x["IsSelected"].ToString() == "True");
            var ids = drs.Select(x => x["ID"].ToString()).ToList();
            if (cbPt.Checked)
            {
                var dtPt =await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.targetConnectionString, $@"SELECT id,pkey,dname FROM sit_device_gen_pt_15min WHERE sid={MySQLHelper.ConvertGuidToSql(drSite["id"].ToString())} and pkey IN ({MySQLHelper.ConvertListToStr(ids)})");
                if (dtPt != null && dtPt.Rows.Count > 0)
                {
                    MessageBox.Show($@"已存在功率设备{string.Join(",", dtPt.AsEnumerable().Select(x => x["pkey"].ToString()))}！");
                    return;
                }
            }
            if (cbWh.Checked)
            {
                var dtPt =await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.targetConnectionString, $@"SELECT id,pkey,dname FROM sit_device_gen_wh_15min WHERE sid={MySQLHelper.ConvertGuidToSql(drSite["id"].ToString())} and pkey IN ({MySQLHelper.ConvertListToStr(ids)})");
                if (dtPt != null && dtPt.Rows.Count > 0)
                {
                    MessageBox.Show($@"已存在电量设备{string.Join(",", dtPt.AsEnumerable().Select(x => x["pkey"].ToString()))}！");
                    return;
                }
            }
            List<string> sqlList = new List<string>();
            //插入数据
            foreach (var item in dtA.AsEnumerable().Where(x => x["IsSelected"].ToString() == "True"))
            {
                if (cbPt.Checked)
                {
                    sqlList.Add($@"insert into sit_device_gen_pt_15min(pkey,dname,sid,isdel,enddate)VALUES ({MySQLHelper.ConvertGuidToSql(item["ID"].ToString())},{MySQLHelper.ConvertGuidToSql(item["NAME"].ToString())},{MySQLHelper.ConvertDecimalToSql(drSite["id"].ToString())},{isDel},{txtEndDate.Text})");
                }
                if (cbWh.Checked)
                {
                    sqlList.Add($@"insert into sit_device_gen_wh_15min(pkey,dname,sid,isdel,enddate)VALUES ({MySQLHelper.ConvertGuidToSql(item["ID"].ToString())},{MySQLHelper.ConvertGuidToSql(item["NAME"].ToString())},{MySQLHelper.ConvertDecimalToSql(drSite["id"].ToString())},{isDel},{txtEndDate.Text})");
                }
            }
            if (await MySQLHelper.ExecuteSqlAsync(MySQLHelper.targetConnectionString, sqlList))
            {
                MessageBox.Show("新建设备成功");
            }
            else
            {
                MessageBox.Show("新建设备失败");
            }
        }

        private async void btnSearch_Click(object sender, EventArgs e)
        {
            var dtA =await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.targetConnectionString, $@"SELECT id,`site_name`,pkey,parent_pkey FROM site_15min WHERE `site_name` LIKE '%{txtSiteName.Text}%'");
            if (dtA == null || dtA.Rows.Count == 0)
            {
                MessageBox.Show("没有查询到相关数据");
                return;
            }
            if (!dgSite.Columns.Contains("IsSelected"))
            {
                // 创建一个DataGridViewCheckBoxColumn
                DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
                checkBoxColumn.HeaderText = "选中";
                checkBoxColumn.Name = "IsSelected";
                checkBoxColumn.DataPropertyName = "IsSelected";
                // 将勾选列添加到DataGridView
                dgSite.Columns.Add(checkBoxColumn);
            }

            // 为DataTable添加对应的列
            dtA.Columns.Add("IsSelected", typeof(bool));
            dtA.Columns["IsSelected"].SetOrdinal(0); // 将勾选列设置为第一列

            // 设置不允许新增行
            dgSite.AllowUserToAddRows = false;

            dgSite.AllowUserToDeleteRows = false; // 禁止删除行

            SiteBindingSource.DataSource = dtA;
            dgSite.DataSource = SiteBindingSource;

            dgSite.Columns["id"].HeaderText = "ID";
            dgSite.Columns["site_name"].HeaderText = "名称";
            dgSite.Columns["pkey"].HeaderText = "数元平台站点ID";
            dgSite.Columns["parent_pkey"].HeaderText = "数元上级节点ID";
            dgSite.AutoResizeColumns();

            dgSite.CellContentClick += dgSite_CellContentClick;

            if (!dgDevice.Columns.Contains("IsSelected"))
            {
                // 创建一个DataGridViewCheckBoxColumn
                DataGridViewCheckBoxColumn checkBoxColumn2 = new DataGridViewCheckBoxColumn();
                checkBoxColumn2.HeaderText = "选中";
                checkBoxColumn2.Name = "IsSelected";
                checkBoxColumn2.DataPropertyName = "IsSelected";
                // 将勾选列添加到DataGridView
                dgDevice.Columns.Add(checkBoxColumn2);
            }

            // 设置不允许新增行
            dgDevice.AllowUserToAddRows = false;

            dgDevice.AllowUserToDeleteRows = false; // 禁止删除行

            dgDevice.ContextMenuStrip = contextMenuStrip1;
        }

        private async void dgSite_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // 检查点击的是否是IsSelected列
            if (e.RowIndex >= 0)
            {
                if (e.ColumnIndex == dgSite.Columns["IsSelected"].Index)
                {
                    for (int i = 0; i < dgSite.Rows.Count; i++)
                    {
                        if (i != e.RowIndex)
                        {
                            // 取消其他行IsSelected列的勾选
                            dgSite.Rows[i].Cells["IsSelected"].Value = false;
                        }
                    }
                    //var dr = SiteBindingSource.Current as DataRowView;
                    DataRowView drv = SiteBindingSource[e.RowIndex] as DataRowView;
                    if (drv == null)
                    {
                        return;
                    }
                    var dtA =await MySQLHelper.GetDataTableBySqlAsync(MySQLHelper.soureConnectionString, $@"SELECT ID,CLASSNAME,`NAME`,PATHID FROM dev_powersystemresource WHERE `PATHID` LIKE '%\\\\{drv["pkey"]}%' AND CLASSNAME = 'Bay' order by PATHID");
                    if (dtA.Rows.Count == 0)
                    {
                        MessageBox.Show("没有查询到相关数据");
                        return;
                    }
                    // 为DataTable添加对应的列
                    dtA.Columns.Add("IsSelected", typeof(bool));
                    dtA.Columns["IsSelected"].SetOrdinal(0); // 将勾选列设置为第一列

                    DeviceBindingSource.DataSource = dtA;
                    dgDevice.DataSource = DeviceBindingSource;

                    dgDevice.Columns["ID"].HeaderText = "ID";
                    dgDevice.Columns["CLASSNAME"].HeaderText = "类型";
                    dgDevice.Columns["NAME"].HeaderText = "名称";
                    dgDevice.Columns["PATHID"].HeaderText = "路径";
                    dgDevice.AutoResizeColumns();

                    lbCount.Text = dtA.Rows.Count.ToString();
                }
            }

        }


        private void txtParentID_KeyPress(object sender, KeyPressEventArgs e)
        {
            // 允许输入数字、退格键和负号（仅在开头）
            if (!char.IsDigit(e.KeyChar) && e.KeyChar != '\b')
            {
                //不需要负号
                //if (e.KeyChar == '-' && textBox1.Text.Length == 0)
                //{
                //    return;
                //}
                e.Handled = true;
            }
        }

        private void txtEndDate_KeyPress(object sender, KeyPressEventArgs e)
        {
            // 允许输入数字、退格键和负号（仅在开头）
            if (!char.IsDigit(e.KeyChar) && e.KeyChar != '\b')
            {
                e.Handled = true;
            }
        }

        private void tsmAllSelect_Click(object sender, EventArgs e)
        {
            DataTable dtA = DeviceBindingSource.DataSource as DataTable;
            if (dtA != null && dtA.Rows.Count > 0)
            {
                //for (int i = 0; i < dgDevice.Rows.Count; i++)
                //{
                //    // 取消其他行IsSelected列的勾选
                //    dgDevice.Rows[i].Cells["IsSelected"].Value = true;
                //}

                foreach (var dr in dtA.AsEnumerable())
                {
                    if (dr.RowState == DataRowState.Deleted)
                    {
                        continue;
                    }

                    dr["IsSelected"] = true;
                    dr.EndEdit();
                }
                dgDevice.EndEdit();

            }
        }

        private void tsmAllCancel_Click(object sender, EventArgs e)
        {
            DataTable dtA = DeviceBindingSource.DataSource as DataTable;
            if (dtA != null && dtA.Rows.Count > 0)
            {
                //for (int i = 0; i < dgDevice.Rows.Count; i++)
                //{
                //    // 取消其他行IsSelected列的勾选
                //    dgDevice.Rows[i].Cells["IsSelected"].Value = true;
                //}

                foreach (var dr in dtA.AsEnumerable())
                {
                    if (dr.RowState == DataRowState.Deleted)
                    {
                        continue;
                    }

                    dr["IsSelected"] = false;
                    dr.EndEdit();
                }
                dgDevice.EndEdit();

            }
        }
    }
}
